package com.atguigu.tingshu.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @BelongsProject: tingshu-parent
 * @BelongsPackage: com.atguigu.tingshu.common.feign
 * @Author: jiangyi
 * @CreateTime: 2025-10-16  09:25
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class FeignInterceptor implements RequestInterceptor {
    /**
     * feign拦截器,feign在进行远程调用时并不关心请求头的信息，可能会导致请求头丢失，所以显式注入请求头信息
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            String token = servletRequestAttributes.getRequest().getHeader("token");
            requestTemplate.header("token", token);
        }
    }
}
